package org.abc.fund.controller.user;

import jakarta.validation.Valid;
import org.abc.fund.service.user.request.create_user.CreateUserRequest;
import org.abc.fund.controller.user.response.UserResponse;
import org.abc.fund.entity.user.User;
import org.abc.fund.service.user.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 用户控制器类，处理与用户相关的HTTP请求 */
@RestController
@RequestMapping("/api/users")
public class UserController {
  private final UserService userService;

  /**
   * 构造函数注入UserService
   *
   * @param userService 用户服务接口，用于执行用户相关的业务逻辑
   */
  public UserController(UserService userService) {
    this.userService = userService;
  }

  /**
   * 用户注册接口
   *
   * <p>该方法通过POST请求处理用户注册逻辑，接收用户信息请求体，验证信息有效性后创建新用户
   *
   * @param createUserRequest 用户创建请求对象，包含用户注册所需的信息
   * @return 返回新创建用户的响应实体和HTTP状态码
   */
  @PostMapping("/register") // 使用/register更符合语义
  public ResponseEntity<UserResponse> registerUser(
      @Valid @RequestBody CreateUserRequest createUserRequest) {
    // 调用用户服务创建新用户
    User newUser = userService.createUser(createUserRequest);
    // 返回用户响应对象和HTTP状态码
    return new ResponseEntity<>(UserResponse.fromEntity(newUser), HttpStatus.CREATED);
  }

  @GetMapping
  public ResponseEntity<List<UserResponse>> getAllUsers() {
    List<User> users = userService.getAllUsers();
    List<UserResponse> userResponses = users.stream().map(UserResponse::fromEntity).toList();
    return new ResponseEntity<>(userResponses, HttpStatus.OK);
  }
}
